package util;

import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

/**
 * Logger utility functions
 * @author Sion
 */
public class LoggerUtil {

	/**
	 * Returns a logger to log all levels to console and file
	 * @param name
	 * @return
	 */
	public static Logger getLogger(String name) {
		Logger logger = Logger.getLogger(name);
		logger.setUseParentHandlers(false);
		ConsoleHandler consoleHandler = new ConsoleHandler();
		consoleHandler = (ConsoleHandler)setupHandler(consoleHandler);
		logger.addHandler(consoleHandler);
		try {
		    boolean append = true;
		    // TODO set path to ProgramData here
		    FileHandler fileHandler = new FileHandler("FootballStatsManager.log", append);
		    fileHandler = (FileHandler)setupHandler(fileHandler);
		    logger.addHandler(fileHandler);
		} catch (IOException e) {
			logger.warning("Error setting up file handler for logging: " + e );
		}
		// TODO why do I need this if useParentHandlers = false?
		// TODO why does the log level not work for the file handler?
		logger.getParent().setLevel(Level.ALL);
		return logger;
	}
	
	private static StreamHandler setupHandler(StreamHandler handler) {
		handler.setLevel(Level.ALL);
		LogFormatter logFormatter = new LogFormatter();
		handler.setFormatter(logFormatter);
		return handler;
	}

}
